(function($) {
  window.Router = function(id) {
    var self = this;

    self.hashList = {}; /* 路由表 */
    self.index = null;
    self.key = '!';
    self.id = id;

    window.onhashchange = function() {
      self.reload();
    };
  };

  /**
   * 添加路由,如果路由已经存在则会覆盖
   */
  Router.prototype.add = function(addr, page) {
    var self = this;

    self.hashList[addr] = page;
  };

  /**
   * 删除路由
   */
  Router.prototype.remove = function(addr) {
    var self = this;

    delete self.hashList[addr];
  };

  /**
   * 设置主页地址
   */
  Router.prototype.setIndex = function(index) {
    var self = this;

    self.index = index;
  };

  /**
   * 跳转到指定地址
   */
  Router.prototype.go = function(addr) {
    var self = this;

    window.location.hash = '#' + self.key + addr;
  };

  /**
   * 重载页面
   */
  Router.prototype.reload = function() {
    var self = this;

    var hash = window.location.hash.replace('#' + self.key, '');
    var addr = hash.split('/')[0];
    var page = getPage(addr, self.hashList);
    if(page != false) {

        $.get(page, function(res) {
            $("#"+self.id).html(res);
        });
    } else {
      self.index && self.go(self.index);
    }
  };

  /**
   * 开始路由
   */
  Router.prototype.start = function() {
    var self = this;

    self.reload();
  }

  /**
   * 获取页面
   */
  function getPage(addr, hashList) {
    for(var key in hashList) {
      if(key == addr) {
        return hashList[key];
      }
    }
    return false;
  }
})(jQuery);